<template>
	<div class="tikuBg" :class="darkmode ? 'darkmode' : ''">
		<u-sticky>
			<div class="banner">
				<image src="https://www.baixuemianshi.com/zhuanti/images/swiper_xcx2.jpg" mode="widthFix"></image>
			</div>
		</u-sticky>
		<div class="container">
			<div class="answerBox">
				<h3>
					<u-parse :content="tm.title"></u-parse>
				</h3>
				<div class="audioBox" v-if="ResultUrl">
					<div class="playBtn"  @click="changePlay()">
						<div v-if="!isPlay">
							<u-icon name="play-circle-fill" color="#2979ff" size="48" ></u-icon> 立即播放
						</div>
						<div v-else>
							<u-icon name="pause-circle-fill" color="#2979ff" size="48"></u-icon> 点击暂停
						</div>
					</div>
					<div class="backRate">
						<div class="nowRate" @click="showRate=true">
							<u-button type="primary" :plain="true" :text="nowRate + 'x'" size="mini"></u-button>
						</div>
						<u-picker :show="showRate" :columns="[rateList]" @confirm="changeRate" :defaultIndex="[1]" @cancel="showRate = false" :closeOnClickOverlay="true" :immediateChange="true"></u-picker>
					</div>
				</div>
				<div class="audioBox" v-else>
					<u-button v-if="!makeEnd" type="error" text="生成音频" size="small" @click="makeAudio"></u-button>
					<div v-else>生成中...</div>
				</div>
				<ul class="tags">
					<li><u-tag :text="tm.leixing" size="mini" type="success"></u-tag></li>
				</ul>
				
				<p class="answerStyle" v-if="tm.answerDetail">
					<u-parse :content="tm.answerDetail"></u-parse>
				</p>
				<p class="answerStyle" v-if="tm.silu">
					<u-parse :content="tm.silu"></u-parse>
				</p>
				<!-- <div class="adBox">
					<image src="https://www.baixuemianshi.com/zhuanti/images/swiper_xcx2.jpg" mode="widthFix"></image>
				</div> -->
			</div>
			<div class="answerBox" @click="toKesu">
				<div class="kesu">
					<image src="https://www.baixuemianshi.com/zhuanti/kesu/images/banner2.jpg" mode="widthFix"></image>
				</div>
				<div class="introText">
					<div class="btn"><u-button type="error" shape="circle" text="点击提交意见"></u-button></div>
				</div>
			</div>
			
			<div class="tools">
				<div class="icon" @click="showTools = !showTools">
					<u-icon name="grid"></u-icon>
				</div>
				<div class="toolsList" :class="showTools ? 'show': ''">
					<div class="item">
						<h4>深色模式</h4>
						<div class="switchBox">
							<u-switch v-model="darkmode" @change="changedarkmode" size="20"></u-switch>
						</div>
					</div>
				</div>
			</div>

			<canvas canvas-id="waterMark" class="waterMark" style="width: 100vw; height: 100vh;"></canvas>
			<image :src="waterMarkUrl" class="waterMark-bg" style="width: 100vw; height: 100vh;"></image>
		</div>

	</div>
</template>

<script>
	let plugin = requirePlugin("QCloudAIVoice");// 引入插件
	plugin.setQCloudSecret('1259791820', 'AKIDmT7LXYK0b9kVM3g6bIpS3UmsogR8kGev', new Date(), true); 
	import {
		mapActions
	} from 'vuex';
	const db = wx.cloud.database()
	export default {
		data() {
			return {
				tmid: "",
				tm: "",

				waterMarkUrl: "",
				windowWidth: 100,
				windowHeight: 100,
				
				
				ResultUrl:"",
				audioContext:"",
				isPlay: false,
				makeEnd: false,
				nowRate:1,
				rateList:[0.5,1,1.2,1.5,1.8,2],
				showRate:false,
				darkmode:false,
				showTools: false
			}
		},
		onLoad(options) {
			this.tmid = options.tmid
			this.getTimu()
			
			let dark = uni.getStorageSync("darkmode")
			if(dark){
				this.darkmode = true
				this.setDark()
			}
		},
		onShow() {
			if (wx.setVisualEffectOnCapture) {
				wx.setVisualEffectOnCapture({
					visualEffect: 'hidden',
					success: (res) => {
						console.log('success回调', res)
					},
				})
			}
		},
		onHide() {
			if (wx.setVisualEffectOnCapture) {
				wx.setVisualEffectOnCapture({
					visualEffect: 'none',
					success: (res) => {
						console.log('success回调', res)
					},
				})
			}
		},
		computed: {
			userphone() {
				return this.$store.getters.userphone ? this.$store.getters.userphone : '';
			},
		},
		created() {
			let that = this;

		},
		mounted() {


			if (this.userphone) {
				this.drawWaterMark('雪恒教育-白雪面试 ' + this.userphone);
			} else {
				this.drawWaterMark('雪恒教育-白雪面试');
			}

		},
		methods: {
			...mapActions(['LogSetPhone']),
			changedarkmode(e){
				this.darkmode = e
				uni.setStorageSync("darkmode",this.darkmode)
				this.setDark()
			},
			setDark(){
				let that = this
				if(this.darkmode){
					uni.setNavigationBarColor({
						frontColor: '#ffffff', 
						backgroundColor: '#11101c', 
						navigationBarTextStyle: '#ffefdd',
					})
				}else{
					uni.setNavigationBarColor({
						frontColor: '#000000', 
						backgroundColor: '#ffffff', 
						navigationBarTextStyle: '#ffffff',
					})
				}
				
			},
			getTimu() {
				let that = this
				db.collection("nbhd_chanyan").doc(that.tmid).get({
					success: res => {
						that.tm = res.data
						if(that.tm.audio){
							that.playAudio(that.tm.audio)
							return
						}
						// var t_file = wx.getStorageSync(that.tmid)
						// if(t_file){
						// 	console.log(t_file)
						// 	that.playAudio(t_file)
						// }
					}
				})
			},
			makeAudio(){
				let that = this
				db.collection('nbhd_chanyan').doc(that.tmid).get({
					success: (res)=>{
						if(res.data.makeId){
							that.wordYun(res.data.makeId)
						}else{
							that.getAudio()
						}
					}
				})
				
				that.makeEnd = true
			},
			getAudio() {
				let that = this
				wx.cloud.callFunction({
					name:"submitTxt",
					data:{
						txt:that.tm.answerDetail.replaceAll('<br>','')
						// txt:'这里是长文本语音'
					}
				}).then(res=>{
					db.collection('nbhd_chanyan').doc(that.tmid).update({
						data:{
							makeId: res.result
						},
						success:function(){
							that.wordYun(res.result)
						},
						fail:function(){
							
						}
					})
					
				})
			},
			wordYun(id) {
				var that = this;
				// var content = e;
				wx.cloud.callFunction({
					name:"submitId",
					data:{
						// txt:that.tm.answerDetail.replaceAll('<br>','。')
						TaskId:id
					}
				}).then(res=>{
					console.log(res)
					if(res.result.status != 'success'){
						setTimeout(function(){
							that.wordYun(id)
						},5000)
					}else{
						wx.setStorage({
							key: that.tmid,
							data: res.result.link
						})
						that.playAudio(res.result.link)
						
						
					}
				})
			},
			playAudio(link){
				let that = this
				console.log(link)
				wx.downloadFile({
					url: link,
					success: function(res) {
						let path = res.tempFilePath
						console.log("my path")
						console.log(path)
						that.ResultUrl = path
						if(link.includes('www.baixuemianshi.com')){
							that.audioContext = wx.createInnerAudioContext(); // 创建内部音频上下文对象
							that.audioContext.src = path; // 设置音频源为指定的URL地址
							that.audioContext.playbackRate = that.nowRate
							that.audioContext.onPlay(() => { // 监听开始播放事件
								console.log('开始播放');
							});
							that.audioContext.onError((res) => { // 监听播放错误事件
								console.log(res.errMsg);
								console.log(res.errCode);
							});
						}else{
							that.uploadAudio(path)
						}
						
						
						
						// that.audioContext.play(); // 启动播放
						
						
						
						// that.innerAudioContext.src = path
						// that.innerAudioContext.play(); //播放音频
					}
				})
			},
			uploadAudio(info) {
				let that = this
				wx.showLoading({
					title: '音频上传中',
				})
				wx.uploadFile({
					url: 'https://www.baixuemianshi.com/zhuanti/upload_img/upload_audio.php', //仅为测试地址，填写你的url即可
					filePath: info,
					name: 'file',
					success: function(res) {
						if (res.statusCode == '200') {
							console.log(res)
							let path = JSON.parse(res.data)
							db.collection('nbhd_chanyan').doc(that.tmid).update({
								data:{
									audio: 'https://www.baixuemianshi.com/zhuanti/upload_img/upload_audio/' + path.data
								},
								success:function(){
									that.audioContext = wx.createInnerAudioContext(); // 创建内部音频上下文对象
									that.audioContext.src = info; // 设置音频源为指定的URL地址
									that.audioContext.playbackRate = that.nowRate
									that.audioContext.onPlay(() => { // 监听开始播放事件
										console.log('开始播放');
									});
									that.audioContext.onError((res) => { // 监听播放错误事件
										console.log(res.errMsg);
										console.log(res.errCode);
										
										db.collection('nbhd_chanyan').doc(that.tmid).update({
											data:{
												audio:"",
												makeId:""
											},
											success:res => {
												that.ResultUrl = ""
												that.makeAudio()
												
											}
										})
									});
								},
								fail:function(){
									
								}
							})
							
							
						}
					},
					error: function(res) {
						console.log("上传失败!")
					},
				})
				wx.hideLoading();
			},
			changePlay(){
				if(this.isPlay){
					this.audioContext.pause()
					this.isPlay = false
				}else{
					this.audioContext.play()
					this.isPlay = true
				}
			},
			changeRate(e){
				let that = this
				console.log(e)
				that.nowRate = e.value[0]
				that.audioContext.playbackRate = that.nowRate
				that.showRate = false
			},
			drawWaterMark(text) {
				this.getDeviceInfo().then(response => {
					const w = response.windowWidth;
					const h = response.windowHeight;
					this.windowWidth = w;
					this.windowHeight = h;
					//创建canvas绘制上下文
					const canvas = uni.createCanvasContext("waterMark", this);
					canvas.clearRect(0, 0, w, h)
					//开始创建一个路径，需要调用fill或者stroke才会使用路径进行填充或描边。
					canvas.beginPath();
					canvas.setFontSize(18);
					canvas.setFillStyle('rgba(0, 0, 0, 0.1)');
					canvas.rotate(-30 * Math.PI / 180)
					if (text) {
						text = this.trim(text)
					}
					const maxWidth = text.length * 18
					for (let x = 0; x < 10; x++) {
						for (let y = 0; y < 20; y++) {
							//在画布上绘制被填充的文本。
							canvas.fillText(text, (maxWidth + 40) * x - 400, 90 * y + 20);
						}
					}
					//将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中。
					canvas.draw(false, () => {
						//把当前画布指定区域的内容导出生成指定大小的图片
						uni.canvasToTempFilePath({
							canvasId: "waterMark",
							complete: (res) => {
								this.waterMarkUrl = res.tempFilePath
							}
						}, this)
					})
				});
			},
			trim(str) {
				let trimStr = '';
				const reg = /[\t\r\f\n\s]*/g;
				if (typeof str === 'string') {
					trimStr = str.replace(reg, '');
				}
				return trimStr
			},
			/**
			 * 获取当前设备的信息
			 * **/
			getDeviceInfo() {
				return new Promise((resolve, reject) => {
					uni.getSystemInfo({
						success: (sysInfo) => {
							resolve(sysInfo)
						}
					})
				})
			},

			toKesu() {
				wx.navigateToMiniProgram({
					appId: "wxc6f7726f4395ee3d",
					path: "pages/huodong/kesu/index",
					success(res) {
						console.log(res);
					},
					fail(e) {
						console.log(e);
					}
				});
			}
		},
		components: {

		}
	};
</script>

<style>
	@import url(./index.css);
</style>